package com.jcss.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {
	private int buffer = 1 * 1024 * 1024;
	private int maxSize = 100 * 1024 * 1024;

	public void init() throws ServletException {
		super.init();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();

		//
		String p = session.getServletContext().getRealPath(
				"/upload/" + UUID.randomUUID());

		File uploadPath = new File(p);
		if (!uploadPath.exists())
			uploadPath.mkdirs();

		File tempPathFile = new File(p + "/temp/");
		if (!tempPathFile.exists()) {
			tempPathFile.mkdirs();
		}

		PrintWriter out = response.getWriter();

		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Set factory constraints
			factory.setSizeThreshold(buffer);
			factory.setRepository(tempPathFile);

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Set overall request size constraint
			upload.setSizeMax(maxSize);

			List<FileItem> items = upload.parseRequest(request);
			Map<String, String> map1 = new HashMap<String, String>();
			Map<String, String> map2 = new HashMap<String, String>();

			Iterator<FileItem> i = items.iterator();
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				String fileName = fi.getName();

				if (fileName != null) {
					File fullFile = new File(fi.getName());
					File savedFile = new File(p, fullFile.getName());
					if (fi.getSize() > 0) {
						fi.write(savedFile);

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			out.write("<script>window.parent.fileupload(-2);</script>");
			out.flush();
		}
	}
}
